<template>
  <div>
    <n-modal
        v-model:show="showDatasourceModalRef"
        :mask-closable="false"
        preset="dialog"
        title="数据源绑定"
        positive-text="确认"
        negative-text="取消"
        @positive-click="onPositiveClick"
        @negative-click="onNegativeClick"
        @after-leave="onNegativeClick"
        style="width: 700px"
    >
      <div>
        <n-tabs v-model:value="CurrentFlow" type="line" animated @click="selectFlowBtn">
          <n-tab-pane :name="item.id" :tab="item.Title" v-for="(item,index) in allFlows" :key="index">
            <template v-if="dataSourceType === DefaultDataSourceType&&CurrentFlow != -99">
              <n-collapse style="max-height: 420px">
                <n-scrollbar style="height: 420px" :distance="10">
                  <n-collapse-item v-for="(node,index) in CurrentFlowNode.processors" :key="index"
                                   :title="node.id+'_'+node.name"
                                   :name="node.id">
                    <n-tag round :bordered="false" class="node-out-param"
                           :type="SelectedNodeOutParams===(node.id+'_'+out.ParamName)?'success':''"
                           @click="selectNodeOutParam(node,out)"
                           v-for="(out,indexOut) in node.NodeOutParam.OutParams" :key="indexOut">
                      {{ out.ParamName }}
                      <template #icon v-if="SelectedNodeOutParams===(node.id+'_'+out.ParamName)">
                        <n-icon :component="CheckmarkCircle"/>
                      </template>
                    </n-tag>
                  </n-collapse-item>
                </n-scrollbar>
              </n-collapse>
            </template>
            <!--           -99 = 全局变量 -->
            <template v-else-if="CurrentFlow == -99">
              <n-tag round :bordered="false" class="node-out-param"
                     v-for="(GlobalParam,nodeIndex) in GlobalParams" :key="nodeIndex"
                     :type="SelectedNodeOutParams===(GlobalParam.Id+'_'+GlobalParam.Name)?'success':''"
                     @click="selectNodeOutParam(GlobalParam,{nodeId:GlobalParam.Id,ParamName:GlobalParam.Name})">
                {{ GlobalParam.Id }} : {{ GlobalParam.Name }}
                <template #icon v-if="SelectedNodeOutParams===(GlobalParam.Id+'_'+GlobalParam.Name)">
                  <n-icon :component="CheckmarkCircle"/>
                </template>
              </n-tag>
            </template>
            <template v-else>
              <n-tag round :bordered="false" class="node-out-param"
                     v-for="(node,nodeIndex) in CurrentFlowNode.processors" :key="nodeIndex"
                     :type="SelectedNodeOutParams===(node.id+'_'+node.name)?'success':''"
                     @click="selectNodeOutParam(node)">
                {{ node.id }} _ {{ node.name }}
                <template #icon v-if="SelectedNodeOutParams===(node.id+'_'+node.name)">
                  <n-icon :component="CheckmarkCircle"/>
                </template>
              </n-tag>
            </template>
          </n-tab-pane>
        </n-tabs>
      </div>
    </n-modal>
  </div>
</template>
<script setup>
import { ref, watch, onMounted, reactive, computed } from 'vue'
import { useMessage } from 'naive-ui'
import { useStore } from 'vuex';
import FlowRuntimeApi from "@/api/flow/FlowRuntimeApi";
import { CheckmarkCircle } from '@vicons/ionicons5'
import { AppParams } from '@/utils/appParams'
import Utils from "@/vue2-flow/src/utils/Common";

const store = useStore();
const message = useMessage()
const emit = defineEmits(['close'])
const showDatasourceModalRef = ref(false)
const CurrentFlow = ref()
const CurrentFlowNode = ref({ processors: [] })
const FlowStore = useFlowStore();
const GlobalParams = computed(()=>{
  return FlowStore.GlobalParams
})
let SelectedNodeOutParam = reactive({})
let SelectedNodeOutParams = ref('')
const DefaultDataSourceType = ref('NODE_PARAM')
const allFlows = ref()
const props = defineProps({
  show: { type: Boolean, required: true },
  data: { type: Object, required: false },
  paramName: { type: String, required: true },
  dataSourceType: { type: String, required: false, default: 'NODE_PARAM' }
})
import { useFlowStore } from "@/store/modules/flow/flowStore";
import { FlowApi } from "@/api/FlowApi";
import { System } from "@/api/SystemApi";


/**
 * 确认按钮
 */
const onPositiveClick = () => {
  SelectedNodeOutParam.option = 'add'
  if (Utils.IsEmpty(SelectedNodeOutParams.value)) {
    SelectedNodeOutParam.option = 'delete'
  }
  CloseDialog(SelectedNodeOutParam)
}
/**
 * 取消按钮
 */
const onNegativeClick = () => {
  CloseDialog(null)
}

const CloseDialog = (data) => {
  SelectedNodeOutParams.value = ''
  emit('close', data)
}
watch(() => props.show, (nv) => {
  if (!nv) {
    return
  }
  showDatasourceModalRef.value = nv
  const { data, paramName } = props
  if (Utils.IsEmpty(data)) {
    return
  }
  let params = ''
  if (data.datasource) {
    for (let paramsKey in data.datasource.params) {
      if (data.datasource.params[paramsKey] === paramName) {
        params = paramsKey
      }
    }
  }
  SelectedNodeOutParams.value = params
})

/**
 * 加载数据
 * @constructor
 */
const InitComponentEvent = () => {
  allFlows.value = []
  const afs = Object.assign([], FlowStore.AllFlow)
  afs.push({ id: -99, Title: '全局变量' })
  afs.push({ id: -98, Title: '设备信息' })

  allFlows.value = afs
  CurrentFlow.value = afs[0].id
  selectFlowBtn()
}

/**
 * 选中的节点或节点参数
 * @param node
 * @param OutParam
 */
const selectNodeOutParam = (node, OutParam) => {
  const { dataSourceType } = props
  let Key = ''
  if (dataSourceType === DefaultDataSourceType.value
      && node.dataSource !== AppParams.DATA_SOURCE_TYPE.GLOBAL_PARAM) {
    OutParam.nodeId = node.id
    Key = node.id + '_' + OutParam.ParamName
  } else {
    Key = node.Id + '_' + node.Name
  }
  if (Key === SelectedNodeOutParams.value) {
    Key = ''
  }
  SelectedNodeOutParam = OutParam
  SelectedNodeOutParams.value = Key
}
const selectFlowBtn = () => {
  if (CurrentFlow.value === -99) {
    // System.GetGlobalParams().then(res => {
    //   for (let re of res.Data) {
    //     re.id = re.Id
    //     re.name = re.Name
    //   }
    //   GlobalParams.value = res
    // })
  } else {
    const FlowId = CurrentFlow.value
    FlowApi.Get(FlowId).then(res => {
      CurrentFlowNode.value = JSON.parse(res.Data)
    })
    // new FlowRuntimeApi().GetCurrentFlow(CurrentFlow.value, res => {
    //   CurrentFlowNode.value = res
    // })
  }
}
onMounted(() => {
  InitComponentEvent()
})
</script>

<style scoped lang="scss">
.selected-node {
  > div {
    > div {
      color: red;
    }
  }
}

.node-out-param {
  margin: 0 6px 6px 0;
}
</style>
